import {promises as fs} from "fs";
import * as path from "path";

async function writeJsonFile(filePath: string, data: any) {
    await fs.writeFile(filePath, JSON.stringify(data, null, 2), "utf8");
}

async function createPath(filePath: string) {
    const dir = path.dirname(filePath);
    await fs.mkdir(dir, {recursive: true});
}

async function readJsonFile(filePath: string): Promise<any> {
    const data = await fs.readFile(filePath, "utf8");
    return JSON.parse(data);
}

const configPath = "D:\\ct\\breath-config.json";
const configJsonData = {
    socketServerPort: 8088,
    socketServerIp: "127.0.0.1",
    openMockBreathServerFlag: true,
    openMockGateSignalFlag: true
};

const initConfig = async () => {
    console.log("检查是否有配置路径存在");
    await checkOrCreatePath(configPath, configJsonData);
    const configJson = await readJsonFile(configPath);
    console.log(`读取的配置为：${JSON.stringify(configJson)}`);
    Object.assign(breathConfig, configJson);
};

async function checkOrCreatePath(filePath: string, jsonData = null) {
    try {
        await fs.access(filePath);
    } catch (e) {
        console.log(`文件路径不存在，创建路径：${filePath}`);
        await createPath(filePath);
        if (jsonData) {
            console.log(`写入数据：${JSON.stringify(jsonData)}`);
            await writeJsonFile(filePath, jsonData);
        }
    }
}

const breathConfig = {
    socketServerPort: 8088,
    socketServerIp: "127.0.0.1",
    sendPackLength: 5, // 每次积累达到该数据后发送。
    eachDataInterval: 20, // 每个数据的时间间隔
    filterDataMaxLength: 3000, // 得是 sendPackLength 得整数倍

    defaultFilterParams: {
        order: 1,
        low: 12,
        hi: 15,
        yCenter: 550,
        peak_threshold: 0, // 0以上都可以认为是波峰
        valley_threshold: 1100, // 1100以下的都可以任务是波谷
        prominence_threshold: 0, // 显著度。
        min_distance: 1 * 50, // 秒数 * 每秒点数
    },

    stable_breath_condition: {
        peak_error_within: 0.015,
        freq_error_within: 0.015,
    },
    no_show_peak_valley_if_modify_filter_points: 100,
    openCmd: [0x00, 0x01, 0x00, 0x00],
    closeCmd: [0x00, 0x00, 0x00, 0x00],
    openMockBreathServerFlag: true,
    openMockGateSignalFlag: true,
    filterExeName: "filter",

    mockGatewaySignalPort: 8011
};

export {breathConfig, initConfig};
